package com.meiyuetao.myt.pub.web.action;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.web.SimpleController;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.rest.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.entity.RC4Entity;
import com.meiyuetao.myt.customer.entity.SsoUser;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.customer.service.SsoUserService;

@MetaData("移动功能整合")
public class MobileController extends SimpleController {
    @Value("${cfg.rc4.key}")
    private String key;
    @Autowired
    private CustomerProfileService customerProfileService;
    @Autowired
    private SsoUserService ssoUserService;
    private final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @SuppressWarnings("unchecked")
    public HttpHeaders mobileFastRegister() {
        Map<String, Object> jsonMap = Maps.newHashMap();
        try {

            HttpServletRequest request = ServletActionContext.getRequest();
            String param = request.getParameter("param");
            if (StringUtils.isBlank(param)) {
                jsonMap.put("code", "ERROR");
                jsonMap.put("message", "missing parameter:'param'");
                setModel(jsonMap);
                return buildDefaultHttpHeaders();
            }
            String mobilePhone = RC4Entity.decry_RC4_string(param, getKey());
            Pattern p = Pattern.compile("^[1][0-9]{10}$");
            if (p.matcher(mobilePhone).matches() && StringUtils.isNotBlank(mobilePhone)) {
                mobilePhone = mobilePhone.trim();
            } else {
                jsonMap.put("code", "ERROR");
                jsonMap.put("message", "parameter 'param' is not a mobilePhone");
                setModel(jsonMap);
                return buildDefaultHttpHeaders();
            }

            /*
             * 由下面新逻辑代替（） CustomerProfile customerProfile =
             * customerProfileService.findFirstByProperty("mobilePhone",
             * mobilePhone); if (customerProfile != null) { jsonMap.put("code",
             * "OK"); jsonMap.put("message",
             * "find mobilePhone in 'customer_profile'"); setModel(jsonMap);
             * return buildDefaultHttpHeaders(); } else { SsoUser ssoUser =
             * ssoUserService.findFirstByProperty("mobilePhone", mobilePhone);
             * if (ssoUser != null) { jsonMap.put("code", "OK");
             * jsonMap.put("message", "find mobilePhone in 'sso_user'");
             * setModel(jsonMap); return buildDefaultHttpHeaders(); } else {
             * ssoUserService.fastRegisterByMobile(mobilePhone);
             * jsonMap.put("code", "SUCCESS"); jsonMap.put("message",
             * "registered an account by mobilePhone");
             * 
             * } }
             */

            List<SsoUser> ssoUsers = ssoUserService.findByFilter(new PropertyFilter(MatchType.EQ, "mobilePhone", mobilePhone));
            if (!ssoUsers.isEmpty()) {
                // 排序
                Collections.sort(ssoUsers, new Comparator() {
                    @Override
                    public int compare(Object a, Object b) {
                        Date one = ((SsoUser) a).getLastLogonTime();
                        Date two = ((SsoUser) b).getLastLogonTime();
                        return two.compareTo(one);
                    }
                });
                jsonMap.put("code", "OK");
                jsonMap.put("message", "find mobilePhone in 'sso_user' and count=" + ssoUsers.size());
                // 返回用户信息，多条返回 最近登录过的
                jsonMap.put("data", ssoUsers.get(0));
            } else {
                // 2015/7/7 发送异常暂定服务
                // ssoUserService.fastRegisterByMobile(mobilePhone);
                // jsonMap.put("code", "SUCCESS");
                // jsonMap.put("message","registered an account by mobilePhone");
                // // 返回用户信息
                // jsonMap.put("data",
                // ssoUserService.findByProperty("mobilePhone", mobilePhone));
                jsonMap.put("code", "FAILURE");
                jsonMap.put("message", "Manually shut down");
            }
        } catch (Exception e) {
            jsonMap.put("code", "ERROR");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }
        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
    /*
     * TEST public static void main(String[] args) { List<SsoUser> ssoUsers =
     * new ArrayList<SsoUser>(); SsoUser s1 = new SsoUser();
     * s1.setLastLogonTime(new DateTime("2014-1-1").toDate());
     * 
     * SsoUser s2 = new SsoUser(); s2.setLastLogonTime(new
     * DateTime("2015-1-1").toDate());
     * 
     * SsoUser s3 = new SsoUser(); s3.setLastLogonTime(new
     * DateTime("2013-1-1").toDate());
     * 
     * SsoUser s4 = new SsoUser(); s4.setLastLogonTime(new
     * DateTime("2016-2-2").toDate());
     * 
     * ssoUsers.add(s1); ssoUsers.add(s3); ssoUsers.add(s2); ssoUsers.add(s4);
     * // 排序 Collections.sort(ssoUsers , new Comparator() {
     * 
     * @Override public int compare(Object a, Object b) { Date one = ((SsoUser)
     * a).getLastLogonTime(); Date two = ((SsoUser) b).getLastLogonTime();
     * return two.compareTo(one); } });
     * 
     * System.out.println(ssoUsers.get(0).getLastLogonTime()); }
     */
}